<?php
// ----------------------------------------------------------------------
// pn-commerce Shopping Cart Solution for PostNuke
// http://pncommerce.de
// http://www.sourceforge.net/projects/pn-commerce/
//
// It is based on PostKart 0.701QA from
//			Destin LeBlanc [ postkart@zenflesh.com ]
// ----------------------------------------------------------------------
// Source file:  $Source: /cvsroot/pn-commerce/pn-commerce/pnpmpaypalapi.php,v $
//
// Last changes from:  $Author: landseer $
//
// Revision:           $Revision: 1.32 $
//
// Date of revision    $Date: 2004/09/12 15:17:32 $
//  
// ----------------------------------------------------------------------
// LICENSE
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License (GPL)
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// To read the license please visit http://www.gnu.org/copyleft/gpl.html
// ----------------------------------------------------------------------

require_once("modules/pncommerce/common.php");

/**
 * This function is used during the checkout process
 * you can let the user provide special information
 * you need for further processing
 * when you don't need any info just redirect the user to
 * getshippingmethod in the pnuser.php
 * don't forget to bypass all important informations 
 * like BPM,BSM,KID,maxStep
 * it's important when the user jumps back to earlier steps
 *
 * It's important to redirect to getshippingmethod if everything was ok here
 *
 * @param $args['KID'] string CustomerID
 * @param $args['BPM'] string selected Paymethod
 * @param $args['BSM'] string selected Shippingmethod
 * @param $args['maxStep'] int highest Step the user reached in this checkout process
 */
function pncommerce_pmpaypalapi_getdata ($args)
// $BPM
{
	// no need to ak for anything, just forward
	pnRedirect( pnModURL('pncommerce', 'user', 'getshippingmethod',$args ) );
	return true;
}

/**
 * This function is used during the checkout process
 * you can save the provide information here
 * getshippingmethod in the pnuser.php
 * don't forget to bypass all important informations 
 * like BPM,BSM,KID,maxStep
 * it's important when the user jumps back to earlier steps
 *
 * @param $args['KID'] string CustomerID
 * @param $args['BPM'] string selected Paymethod
 * @param $args['BSM'] string selected Shippingmethod
 * @param $args['maxStep'] int highest Step the user reached in this checkout process
 */
function pncommerce_pmpaypalapi_getdataresponse($args)
{
//we don't need to do here something because this function will never be called in this paymethod
}

/**
 * This function is used during the checkout process
 * it's called after the checkout where the user agrees to
 * buy the items, so you can do the rest here to finish the
 * payment process if possible. otherwise just redirect to the next step
 * called processshippingfinal
 * don't forget to bypass all important informations 
 * like ON,KID,maxStep
 * it's important when the user jumps back to earlier steps
 *
 * @param $args['KID'] string CustomerID
 * @param $args['ON']  string order number
 * @param $args['maxStep'] int highest Step the user reached in this checkout process
 */
function pncommerce_pmpaypalapi_processpayment ($args)
// $KID, $BPM, $BSM, maxStep
{ 
    if (!pnModAPILoad('pncommerce', 'user'))
    {
        return showerrorpage("unable to load pnuserapi", __FILE__, __LINE__);
    }
		// we have an order, so we need to display more than before
		$Company = pnModGetVar('pncommerce', 'Company');
		$PayPalEmail = pnModGetVar('pncommerce', 'PayPalEmail');
		$CatalogConfig=pnModAPIFunc( 'pncommerce','admin','getConfigCatalog');
		$CurrencyCode=pnModGetVar('pncommerce', 'PayPalCurrencyCode');
		
		$ImageURL = pnModGetVar('pncommerce', 'PayPalImageURL');
				//Add a Canceled field so we can show the paypal url on the receipt, if the user has not finished the payment
        $cancelargs=array('Method'=>'pmpaypal',
                                        'Function'=>'paymentfailed');
        $successargs=array('Method'=>'pmpaypal',
                                        'Function'=>'paymentsuccess');
         $args['KID']=pnSessionGetVar('KID');
        $cancelargs=array_merge($cancelargs,$args);
        $successargs=array_merge($successargs,$args);
        
        $order =  pnModAPIFunc( 'pncommerce','user','getOrder',
						 array('ON' => $args['ON'],
						 	 'KID' => $args['KID']));

//echo "<pre>";print_r($order);echo "</pre>";
        						 	 
		$sitename = ereg_replace(" ","_",$Company);
		$nukeurl = pnGetBaseURL();
    
    pnSessionSetVar('pncommerce','ON',$args['ON']);	        
    
    //some of them are unnecessary, because we can generate them in the template, but I don't have much time today
    $smarty = new pnRender();
    $smarty->caching = false;
    $smarty->assign( 'PayPalEmail', $PayPalEmail);
    $smarty->assign( 'sitename', $sitename);
    $smarty->assign( 'ON', $args['ON'] );
    $smarty->assign( 'KID', pnVarCleanFromInput('KID') );
    $smarty->assign( 'orderTotal', $order['CartData']['Total'] );
    $smarty->assign( 'ImageURL', $ImageURL );
    $smarty->assign( 'CurrencyCode', $CurrencyCode );
    $smarty->assign( 'MethodForwardOKURL', pnModURL( 'pncommerce', 'user', 'MethodForward', $successargs ) );
    $smarty->assign( 'MethodForwardCancelURL', pnModURL( 'pncommerce', 'user', 'MethodForward', $cancelargs ) );
    $smarty->assign( 'ON', $args['ON'] );
    return $smarty->fetch( "pncommerce_pmpaypal_processpayment.html" );
	//	pnRedirect( pnModURL('pncommerce', 'user', 'processshippingfinal', $args ) );
}


/**
 * This function is used during the checkout process
 * it's called from paypal after the checkout when the user has 
 * aborted the payment of the order
 * Do all necessary stuff here and just redirect to the next step
 * called processshippingfinal
 * don't forget to bypass all important informations 
 * like ON,KID,maxStep
 *
 * @param $args['KID'] string CustomerID
 * @param $args['ON']  string order number
 * @param $args['maxStep'] int highest Step the user reached in this checkout process
 */
function pncommerce_pmpaypalapi_paymentfailed($args)
{
    if (!pnModAPILoad('pncommerce', 'user'))
    {
        return showerrorpage("unable to load pnuserapi", __FILE__, __LINE__);
    }
         $args['KID']=pnSessionGetVar('KID');
         $args['ON']=pnVarCleanFromInput('ON');
		$Company = pnModGetVar('pncommerce', 'Company');
		$PayPalEmail = pnModGetVar('pncommerce', 'PayPalEmail');
		$CatalogConfig=pnModAPIFunc( 'pncommerce','admin','getConfigCatalog');
		$CurrencyCode=pnModGetVar('pncommerce', 'PayPalCurrencyCode');
		
		$ImageURL = pnModGetVar('pncommerce', 'PayPalImageURL');
				//Add a Canceled field so we can show the paypal url on the receipt, if the user has not finished the payment
        $order =  pnModAPIFunc( 'pncommerce','user','getOrder',
						 array('ON' => $args['ON'],
						 	 'KID' => $args['KID']));
  	    $URL="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=$PayPalEmail&currency_code=$CurrencyCode&item_name=order_$Company&item_number=".$args['ON']."&image_url=$ImageURL&no_shipping=1&no_note=1&undefined_quantity=0&amount=".$order['CartData']['Total']."&shipping=0.00&shipping2=0.00";

    $smarty = new pnRender();
    $smarty->caching = false;
    $smarty->assign( 'KID', pnVarCleanFromInput('KID') );
    $smarty->assign( 'ON', pnVarCleanFromInput('ON') );
    $smarty->assign( 'URL', $URL );
    return $smarty->fetch( "pncommerce_pmpaypal_paymentfailed.html" );
}

/**
 * This function is used during the checkout process
 * it's called from paypal after the checkout when the user successfully
 * paid the order
 * Do all necessary stuff here and just redirect to the next step
 * called processshippingfinal
 * don't forget to bypass all important informations 
 * like ON,KID,maxStep
 *
 * @param $args['KID'] string CustomerID
 * @param $args['ON']  string order number
 * @param $args['maxStep'] int highest Step the user reached in this checkout process
 */
function pncommerce_pmpaypalapi_paymentsuccess($args)
{
    if (!pnModAPILoad('pncommerce', 'user'))
    {
        return showerrorpage("unable to load pnuserapi", __FILE__, __LINE__);
    }
    $ON = pnVarCleanFromInput('ON');
		$sql = "UPDATE ".pnConfigGetVar('prefix')."_pncommerce_orders SET
		  OrderStatus=10	WHERE OrderNumber='".(int)$ON."'";
   		$success = pnModAPIFunc ('pncommerce', 'user', 'executesqlDB',
   	                       		 array('sql' => $sql,
                                		 'table' => 'orders',
                                		 'idfield' => 'OrderNumber'));
		if($success===false)
		{
			pnSessionSetVar('errormsg',_PNC_DBERROR);
			return false;
		}

    $smarty = new pnRender();
    $smarty->caching = false;
    $smarty->assign( 'KID', pnVarCleanFromInput('KID') );
    $smarty->assign( 'ON', pnVarCleanFromInput('ON') );
    $smarty->assign( 'url', pnModURL('pncommerce', 'user', 'processshippingfinal', $args ) );
    return $smarty->fetch( "pncommerce_pmpaypal_paymentsuccess.html" );
}

function pncommerce_pmpaypalapi_userinsert()
{
}

function pncommerce_pmpaypalapi_order($args)
// $ON
{
}

function pncommerce_pmpaypalapi_configintro($args)
{
	$Mode = pnVarCleanFromInput ('Mode');

	if (!pnModAPILoad('pncommerce', 'user'))
      {
        return showerrorpage("unable to load pnuserapi", __FILE__, __LINE__);
      }

	if (pnSecAuthAction(0, '::', '::', ACCESS_ADMIN))
	{
	    switch ($Mode)
	    {
	    case 'install':
			pnModSetVar ('pncommerce', 'pmpaypal', 'on');
			pnModSetVar ('pncommerce', 'PayPalEmail', ' ');
			pnModSetVar ('pncommerce', 'PayPalImageURL', ' ');
	    	break;
	    case 'remove':
			pnModDelVar ('pncommerce', 'PayPalEmail');
			pnModDelVar ('pncommerce', 'PayPalImageURL');
			pnModDelVar ('pncommerce', 'pmpaypal');	
	    	break;
	    case 'activate':
	    	pnModSetVar ('pncommerce', 'pmpaypal', 'on');
	    	break;
	    case 'deactivate':
	    	pnModSetVar ('pncommerce', 'pmpaypal', 'off');
	    	break;
	    default:
	    	break;
	    }
       	pnRedirect( pnModAPIFunc('pncommerce','user','pncModURL',
								array('Module'=>'pncommerce', 'Section'=> 'admin', 'Function'=>'paymethodconfig')));
        return true;
    }
	else
	{
		return showerrorpage( _PNC_NOAUTH, __FILE__, __LINE__ );
	}
}

function pncommerce_pmpaypalapi_showoption($args)
// $BPM
{
	extract ($args);
	$temp ="<input type='radio' name='PayMethod' value='pmpaypal'";
	if ( $BPM == 'pmpaypal' )
	{
		$temp .= " checked ";
	}
	$temp .= ">"._PNC_PAYPALORDER."<br>";
	return $temp;
}

function pncommerce_pmpaypalapi_info()
{
	return (""._PNC_PAYPALORDER."");

}

function pncommerce_pmpaypalapi_footermsg($args)
// $ON or $KID, but never both at the same time !!!
// only $ON  : we already have an order and read the fields from there
// only $KID : we don't have an order yet and read from the users table
//
{
	extract ($args);
	$cr = '<br>';
	if ( isset ($ON) )
	{
		// we have an order, so we need to display more than before
		$Company = pnModGetVar('pncommerce', 'Company');
		$PayPalEmail = pnModGetVar('pncommerce', 'PayPalEmail');
		$ImageURL = pnModGetVar('pncommerce', 'PayPalImageURL');

		list ($OTo,$status) = pnModAPIFunc ('pncommerce', 'user', 'readfromDB',
							array('table' => 'orders',
								'fields' => array('OrderTotal','OrderStatus'),
								'required' => array('OrderNumber', $ON)));
		$sitename = ereg_replace(" ","_",$Company);
		$nukeurl = pnGetBaseURL();
		if($status<10)
        {
            $temp =""._PNC_PAYPALORDER.$cr._PNC_WEWILLSHIPUPONPAYMENT.$cr._PNC_CLICKHERETOTRANSFERTOPAYPAL.$cr."</p>
			<form action='https://www.paypal.com/cgi-bin/webscr' method='post'>
			<input type='hidden' name='cmd' value='_xclick'>
			<input type='hidden' name='business' value='$PayPalEmail'>
			<input type='hidden' name='item_name' value='$sitename'>
			<input type='hidden' name='item_number' value='order_$ON'>
			<input type='hidden' name='amount' value='0.00'>
			<input type='hidden' name='image_url' value='$ImageURL'>
			<input type='hidden' name='no_shipping' value='1'>
			<input type='hidden' name='return' value='$nukeurl'>
			<input type='hidden' name='cancel_return' value='$nukeurl'>
			<input type='hidden' name='undefined_quantity' value='0'>
			<input type='hidden' name='shipping' value='0.00'>
			<input type='hidden' name='shipping2' value='0.00'>
			<input type='image' src='http://images.paypal.com/images/x-click-but01.gif' name='submit' alt=''>
			</form>";
        }
        else    
        {
            $temp =""._PNC_PAYPALORDER.$cr._PNC_YOURPAYMENTHASBEENRECEIVED;
        }
	}
	else if ( isset ($KID) )
	{
		//<font class=\"pn-normal\">
		$temp = ""._PNC_SELECTEDPAYMETHOD.": "._PNC_PAYPALORDER.$cr._PNC_WEWILLSHIPUPONPAYMENT.$cr;
	}
	else
	{
		// internal error
		$temp = "Internal error when creating footermsg in paypalapi<br>";
	}
	return $temp;
}

function pncommerce_pmpaypalapi_quietremove ()
{
	pnModDelVar ('pncommerce', 'PayPalEmail');
	pnModDelVar ('pncommerce', 'PayPalImageURL');
	pnModDelVar ('pncommerce', 'pmpaypal');	
}

/**
 * This function is used during the checkout process
 * You can calculate a fee for the selected paymethod here
 *
 * @param $args['SubTotal'] Double the total costs with shipping included
 * @return double 
 * @returns the fee for this paymethod
 */
function pncommerce_pmpaypalapi_getPaymethodTotal($args)
{
//Return 0, this Paymethod is for free
   return 0.;
}

/**
 * Asks for special data for this paymethod, for example minimum fee or default fee, ...
 * Account numbers, ...
 * ****
 * You have to redirect to 'paymethodconfig' when you're done
 * ****
 * @return String 
 * @returns the config page for this paymethod
 */
function pncommerce_pmpaypalapi_config()
{
	if (!pnModAPILoad( 'pncommerce', 'admin'))
    {
        return showerrorpage("unable to load pnadminapi", __FILE__, __LINE__);
    }

	if (pnSecAuthAction(0, '::', '::', ACCESS_ADMIN))
	{
        $Submit = pnVarCleanFromInput( 'Submit' );
        if( !$Submit )
        {
	        $smarty = new pnRender();
            $smarty->caching = false;
		    $PayPalCurrencyCode = pnModGetVar ('pncommerce', 'PayPalCurrencyCode');
		    if(!isset($PayPalCurrencyCode))$PayPalCurrencyCode='EUR';
		    $smarty->assign( 'PayPalCurrencyCode', $PayPalCurrencyCode );
		    $smarty->assign( 'PayPalCurrencyCodes', array('USD'=>'USD', 'CAD'=>'CAD', 'EUR'=>'EUR', 'GBP'=>'GBP', 'JPY'=>'JPY'));
		    $smarty->assign( 'PayPalEmail', pnModGetVar ('pncommerce', 'PayPalEmail') );
		    $smarty->assign( 'PayPalImageURL', pnModGetVar ('pncommerce', 'PayPalImageURL') );
            return $smarty->fetch( 'pncommerce_pmpaypal_configuration.html' );
	    }
	    else // submit is set
	    {
    
    if( !pnSecConfirmAuthKey() ) 
    { 
        return showerrorpage( _PNC_BADAUTHKEY, __FILE__, __LINE__ ); 
    }     
    
        	pnModSetVar('pncommerce','PayPalEmail', pnVarCleanFromInput('PayPalEmail'));
        	pnModSetVar('pncommerce','PayPalImageURL', pnVarCleanFromInput('PayPalImageURL'));
        	pnModSetVar('pncommerce','PayPalCurrencyCode', pnVarCleanFromInput('PayPalCurrencyCode'));
           	pnRedirect( pnModAPIFunc('pncommerce','user','pncModURL',
						array('Module'=>'pncommerce', 'Section'=> 'admin', 'Function'=>'paymethodconfig')));
        	return true;
	    }
	}
	else
	{
		return showerrorpage( _PNC_NOAUTH, __FILE__, __LINE__ );
	}
}

?>
